package com.ynny.dao;

import com.ynny.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;
@Repository
public class UserDaoImpl implements IUserDao{
    @Autowired
    JdbcTemplate jdbcTemplate;
    @Override
    public List<User> findAll() {
        String sql = "select * from user";
        List<User> users = jdbcTemplate.query(sql,new BeanPropertyRowMapper<User>(User.class));
        return users;
    }

    @Override
    public User findById(Integer id) {
        String sql = "select * from user where id = ?";
        User user = jdbcTemplate.queryForObject(sql,new BeanPropertyRowMapper<User>(User.class),id);
        return user;
    }

    @Override
    public int add(User user) {
        String sql = "insert into user(username,password) values(?,?)";
        int update = jdbcTemplate.update(sql, user.getUsername(), user.getPassword());
        return update;
    }

    @Override
    public int update(User user) {
        String sql = "update user set username = ?,password = ?,age = ? where id = ?";
        int update = jdbcTemplate.update(sql, user.getUsername(), user.getPassword(), user.getAge(), user.getId());
        return update;
    }

    @Override
    public int delete(Integer id) {
        String sql = "delete from user where id = ?";
        int delete = jdbcTemplate.update(sql, id);
        return delete;
    }

    @Override
    public User login(String username, String password) {
        String sql = "select * from user where username = ? and password = ?";
        User login = jdbcTemplate.queryForObject(sql,new BeanPropertyRowMapper<User>(User.class),username,password);
        return login;
    }

    @Override
    public User checkUsername(String username) {
        String sql = "select * from user where username = ?";
        List<User> list  = jdbcTemplate.query(sql,new BeanPropertyRowMapper<>(User.class),username);
        if (list .size() == 0 ){
            return null;
        }
        return list.get(0);


    }
}
